// 糖皮质激素类药品
import React from 'react';
import { Select, Row, Col, Button, Spin, Radio, DatePicker, Input, Tooltip, message, Table, Pagination, Form } from 'antd';
import { $http } from '../../../containers/config/https';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import moment from 'moment';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import { Util } from 'tools/index';

const FormItem = Form.Item;
const { Option } = Select;
let user;
const Hormone = Form.create()(
    class OutpatientExpenses extends React.Component {
        constructor({ history }) {
            super();
            this.history = history;
            this.state = {
                value: "nurConfirm",
                searchLoading: false,//查询请求
                tableData: [], //出院患者列表
                columns: [],//列
                showLoading: true,//加载
                checked: false,
                tableType: 'C',
                consultationInfo: {},
                stopDate: '',
                startDate: '',
                locList: [],         //科室
                wardList: [],        //病区
                docList: [],         //医生
                locInfo: [], // 科室名称下拉框
                wardInfo: [],//病区
                wardBedAry: [],//床号
                userInfo: [],//医生
                admReason: [],//费别
                // 主菜单分页数据
                total: 0,
                page: 1,
                pageSize: 10,
                selectData: [],
                locID: '',
                defaultWardID: '',//默认病区
                loading: false,
                allPatData: '',
                exportLoading: false,//导出请求
                locType: [],
                drugDesc : ''
            };
            user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

        }

        componentDidMount() {
            this.loadColumn();
            this.getBaseParams();
            // this.child.handleLoading();
            this.setState({ showLoading: false });
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
        }
        //获取科室下拉
        getBaseParams = () => {
            let data = {
                params: [{
                }],
            }
            $http.post("urlS", this, {
                code: "01040243",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            locType: res.locType
                        })
                    } else {

                    }
                },
                error: function (error) {

                }
            });
        }

        //查询列头数据
        loadColumn = () => {
            let data = {
                params: [{
                    compontName: "Antibacterials",
                    type: this.state.tableType,
                }]
            }
            $http.post('urlDeault', this, {
                code: "01040073",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        let resData = res.result[this.state.tableType];
                        var exportColumn = []
                        if (!Util.isEmpty(resData)) {
                            for (var i = 0; i < resData.length; i++) {
                                if (resData[i].exportFlag == 'Y') {
                                    exportColumn.push(resData[i])
                                }
                            }
                        }
                        for (let index = 0; index < resData.length; index++) {
                            let columnCode = resData[index].code;
                            if ((columnCode == 'admDiag')) {
                                resData[index].onCell = () => {
                                    return {
                                        style: {
                                            maxWidth: 150,
                                            overflow: 'hidden',
                                            whiteSpace: 'nowrap',
                                            textOverflow: 'ellipsis',
                                            cursor: 'pointer'
                                        }
                                    }
                                }
                                resData[index].render = (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
                            }

                        }
                        this.setState({
                            columns: resData,
                            tableWidth: res.totalWidth,
                            exportColumn: exportColumn
                        }
                            , () => {
                                this.handleQuery();
                            })
                    }
                }
            })
        }
        exportData = () => {
            this.setState({
                exportLoading: true,
            })
            const formData = this.props.form.getFieldsValue();
            let data = {}
            data = {
                params: [{
                    hospID: user.hospID,
                    startDate: formData.startDate ? moment(formData.startDate).utcOffset(480).format('YYYY-MM-DD') : '',
                    stopDate: formData.stopDate ? moment(formData.stopDate).utcOffset(480).format('YYYY-MM-DD') : '',
                    patName: formData.patName,
                    locCode:formData.locCode,
                    drugDesc:formData.drugDesc
                }],
                pagination: [{
                    pageSize: '',
                    currentPage: '',
                    sortColumn: 'Date',
                    sortOrder: 'desc'
                }]
            };
            $http.post('urlS', this, {
                code: '05100415',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setState({
                            allPatData: res.result,
                            exportLoading: false,
                        }, () => {
                            //请求
                            setTimeout(() => {
                                this.setState({
                                    exportLoading: false,
                                }, () => {
                                    this.downloadFile()
                                })
                            }, 1000)
                        })
                    } else {
                        this.setState({
                            exportLoading: false,
                        })
                    }
                },
            })
        }

        downloadFile() {
            let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
            try {
                var elemIF = document.createElement('iframe');

                elemIF.src = windowHost + this.state.allPatData;
                elemIF.style.display = 'none';

                document.body.appendChild(elemIF);

                // 防止下载两次

                setTimeout(function () {

                    document.body.removeChild(elemIF)

                }, 1000);

            } catch (e) {

                console.log(e);

            }
        }

        //查询出院患者
        handleQuery = () => {
            this.setState({
                searchLoading: true
            })
            const formData = this.props.form.getFieldsValue();
            let data = {
                params: [{
                    hospID: user.hospID,
                    startDate: formData.startDate ? moment(formData.startDate).utcOffset(480).format('YYYY-MM-DD') : '',
                    stopDate: formData.stopDate ? moment(formData.stopDate).utcOffset(480).format('YYYY-MM-DD') : '',
                    patName: formData.patNo,
                    locCode:formData.locCode,
                    drugDesc:formData.drugDesc
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                    sortColumn: 'Date',
                    sortOrder: 'desc'
                }]
            };
            $http.post('urlS', this, {
                code: '05100414',
                data: data,
                success: (res) => {
                    if (res.errorCode === "0") {
                        for (let index = 0; index < res.result.Data.length; index++) {
                            res.result.Data[index].key = index + 1;
                        }
                        this.setState({
                            total: res.result.TotalCount,
                            tableData: res.result.Data,
                        });
                        this.child.handleLoading();
                        this.setState({
                            searchLoading: false
                        })
                    } else {
                        this.setState({
                            total: 0,
                            tableData: []
                        });
                        this.child.handleLoading();
                        this.setState({
                            searchLoading: false
                        })
                    }
                    this.setState({
                        searchLoading: false
                    })
                }
            });

            this.child.handleLoading();
        }

        // 调用公共组件的连接事件
        onRef = (ref) => {
            this.child = ref
        }
        // 提供修改page和pageSize的回调函数
        compilePage(page, pageSize) {
            // 修改page，或者pageSize
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.handleQuery();

            })
        }
        handleStDateChange = (date, datetimeString) => {
            this.setState({
                startDate: datetimeString
            })
        }
        handleEndDateChange = (date, datetimeString) => {
            // console.log('结束时间1', datetimeString)
            this.setState({
                stopDate: datetimeString
            })
        }
        //登记号
        patNotEnter = (e) => {
            if (e.keyCode = '13') {
                this.setState({
                    patNo: ''
                }, () => {
                    this.handleQuery();
                })
            }
        }
        //住院号
        patMedicalNoEnter = (e) => {
            if (e.keyCode = '13') {
                this.setState({
                    patMedicalNo: ''
                }, () => {
                    this.handleQuery();
                })
            }
        }
        //姓名
        patNameEnter = (e) => {
            if (e.keyCode = '13') {
                this.setState({
                    patName: ''
                }, () => {
                    this.handleQuery();
                })
            }
        }
        //药品名称
        drugDescEnter = (e) => {
            if (e.keyCode = '13') {
                this.setState({
                    drugDesc: ''
                }, () => {
                    this.handleQuery();
                })
            }
        }
        checked = (e) => {
            // console.log('radio checked', e.target.value);
            this.setState({
                value: e.target.value,
            });
        };

        // 重置表单
        resetFields = () => {
            this.props.form.resetFields(); //清空所有

        };
        //首字母大写
        firstToUp = (str) => {
            return str.substring(0, 1).toUpperCase() + str.substring(1);

        }

        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

        //点击行
        onClickRowPublic = (record) => {
            return {
                onClick: () => {
                    let admID = "", patID = "";

                    if (this.state.admID != record.admID) {
                        admID = record.admID;
                        patID = record.patID;
                    }
                    this.setState({
                        admID: admID,
                    })
                    var patientData = {}
                    patientData = {
                        admID: admID,
                        patID: patID,
                    }
                    sessionStorage.setItem('patientData', JSON.stringify(patientData));

                },
            }

        }
        setRowClassNamePublic = (record) => {
            return record.admID == this.state.admID ? 'clickRowStyle' : '';
        }
        render() {
            const {locType} = this.state

            const formItemInput = {
                labelCol: { span: 8 },
                wrapperCol: { span: 16 },
            };
            const formItemLayout = {    // label 和input宽度
                labelCol: { span: 10 },
                wrapperCol: { span: 14 },
            };
            const { getFieldDecorator } = this.props.form;
            const consultationInfo = this.state.consultationInfo;
            // 组件所需参数
            const param = {
                // 表头配置
                isOnRow: true,
                isOnHeadRow: true,
                rowClassName: true,
                columns: this.state.columns,
                // 表格数据state
                data: this.state.tableData,
                // 数据总条数
                total: this.state.total,
                // 当前页数
                page: this.state.page,
                x: this.state.tableWidth
                // // 表格的宽度
                // x: 900,
                // y: store.getState().tableHeight.y -70,
                // height: store.getState().tableHeight.y -25 + 'px',
            }
            let locTypeOpt = []
            locType && locType.map(item => {
                locTypeOpt.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.code)}>{item.descripts}</Option>)
            })
            return (
                <Spin tip="加载中..." spinning={this.state.showLoading} className="department" >
                    <div style={{ width: '100%', height: '100%' }} >
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName="OutPatientQuery"
                            configType="C"
                            onRef={this.onColumnRef}
                            reloadData={this.loadColumn}
                        />
                        <div className="department-header">
                            <Form>
                                <Row>
                                    <Col span={18} className="top-form">
                                        <Row style={{ padding: '0 24px' }}>
                                            <Col span={4}>
                                                <Form.Item label="开始日期：" {...formItemInput}>
                                                    {getFieldDecorator('startDate', {
                                                        initialValue: moment(moment().format("L"), 'YYYY-MM-DD'),
                                                    })(

                                                        <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                            return curDate && curDate > moment().endOf('day');
                                                        }} />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={4}>
                                                <Form.Item label="结束日期：" {...formItemInput}>
                                                    {getFieldDecorator('stopDate', {
                                                        initialValue: moment(moment().format("L"), 'YYYY-MM-DD'),
                                                    })(
                                                        <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                            return curDate && curDate > moment().endOf('day');
                                                        }} />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={5} >
                                                <FormItem {...formItemInput} label='科室'>
                                                    {getFieldDecorator('locCode', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '' }],
                                                    })(
                                                        <Select showSearch allowClear optionFilterProp="role" >
                                                            {locTypeOpt}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={4}>
                                                <Form.Item label="登记号：" {...formItemInput}>
                                                    {getFieldDecorator('patNo', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '请输入姓名' }]
                                                    })(
                                                        <Input onPressEnter={this.patNameEnter} />
                                                    )}

                                                </Form.Item>
                                            </Col>
                                            <Col span={4}>
                                                <Form.Item label="药品名称：" {...formItemInput}>
                                                    {getFieldDecorator('drugDesc', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '请输入药品名称' }]
                                                    })(
                                                        <Input onPressEnter={this.drugDescEnter} />
                                                    )}

                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </Col>
                                    <Col span={5} style={{ marginLeft: '33px' }}>
                                        <Row style={{ marginBottom: '20px', marginTop: '5px' }}>
                                            <Button type="primary" onClick={this.handleQuery} loading={this.state.searchLoading} style={{ marginRight: '30px' }}>查询</Button>
                                            <Button style={{ marginRight: '30px' }} onClick={this.resetFields}>清屏</Button>
                                            <Button type="primary" style={{ marginRight: '30px' }} disabled={Util.isEmpty(this.state.tableData)} loading={this.state.exportLoading}
                                                onClick={this.exportData}>导出</Button>
                                        </Row>
                                    </Col>
                                </Row>
                            </Form>
                        </div>
                        <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                        <div style={{ padding: '24px 24px 0 24px' }}>



                            {/* handelThis将夫组件的属性与方法给子组件访问 */}
                            <PubilcTablePagination
                                param={param}
                                setRowClassNamePublic={this.setRowClassNamePublic}
                                onClickRowPublic={this.onClickRowPublic}
                                handelThis={this}
                                onRef={this.onRef}
                            />
                        </div>

                    </div>
                </Spin>
            )
        }
    }
)
export default Hormone;
